

let ci = 1;
const reducer = function (state, action) {
    switch (action.type) {
        case "increment":
            return Object.assign({}, state, {
                items: [...state.items, { desc: action.desc }]
            });
        case "finished":
            {
                const ni = [...state.items];
                const i = ni.indexOf(action.desc);
                ni[i] = Object.assign({}, ni[i], { finished: true });
                return Object.assign({}, state, {
                    items: ni
                });
            }
        case "remove":
            {
                const i = state.items.findIndex(item => item.desc === action.desc);
                const ni = [...state.items];
                ni.splice(i, 1);
                // console.log(ni);
                return Object.assign({}, state, {
                    items: ni
                });
            }
        case "sort":
            {
                const unsorted = [...state.items];
                const tmpSort = state.sort;
                const sorted = unsorted.sort((a, b) => {
                    if (tmpSort > 0) {
                        return a.desc > b.desc ? 1 : -1;
                    } else {
                        return a.desc < b.desc ? 1 : -1;
                    }
                })
                ci = ci + 1;
                return Object.assign({}, state, {
                    items: sorted, sort: tmpSort > 0 ? -1 : 1
                });
            }
        default:
            return state;
    }
}

export default reducer;